import { defineStore } from 'pinia'
import type { Item } from '../types/Item'

/**
 * 物品信息存储模块
 * 负责管理积分兑换物品的全局状态
 */
export const useItemStore = defineStore('item', {
    // 持久化配置
    persist: {
        storage: localStorage,
        paths: ['itemList', 'currentItem', 'filter']
    },
    state: () => ({
        // 所有物品列表
        itemList: [] as Item[],
        // 当前选中的物品
        currentItem: null as Item | null,
        // 加载状态
        loading: false,
        // 筛选条件
        filter: {
            minPoints: 0,
            maxPoints: Infinity,
            inStockOnly: false
        }
    }),
    actions: {
        /**
         * 获取所有物品
         */
        async fetchAllItems() {
            this.loading = true
            try {
                // this.itemList = await itemApi.getAllItems()
            } finally {
                this.loading = false
            }
        },

        /**
         * 设置筛选条件
         * @param filter - 筛选条件对象
         */
        setFilter(filter: Partial<{ minPoints: number, maxPoints: number, inStockOnly: boolean }>) {
            this.filter = { ...this.filter, ...filter }
        },

        /**
         * 重置筛选条件
         */
        resetFilter() {
            this.filter = {
                minPoints: 0,
                maxPoints: Infinity,
                inStockOnly: false
            }
        }
    },
    getters: {
        /**
         * 获取筛选后的物品列表
         */
        filteredItems(state): Item[] {
            return state.itemList.filter(item => {
                const pointsMatch = item.exchangePoints >= state.filter.minPoints &&
                    item.exchangePoints <= state.filter.maxPoints
                const stockMatch = !state.filter.inStockOnly || item.itemStock > 0
                return pointsMatch && stockMatch
            })
        },

        /**
         * 获取库存紧张的物品（库存小于5）
         */
        lowStockItems(state): Item[] {
            return state.itemList.filter(item => item.itemStock > 0 && item.itemStock < 5)
        }
    }
})
